import socket
import os

SERVERHOST,SERVERPORT=socket.gethostbyname(socket.gethostname()),6666



if(  __name__ == "__main__" ):
    clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    clientsocket.connect((SERVERHOST,SERVERPORT))
    while( True ):
        commandline=input(">> ")

        if("STOR" in  commandline):
            fileName=commandline.split(" ")[-1]
            with open(fileName,"rb") as f: 
                clientsocket.send(bytes("STOR\r\n"+fileName+"\r\n"+str(os.stat(fileName).st_size)+"\r\n",encoding="utf-8")+f.read())
        
        elif("RETR" in  commandline):
            cmd,fileName=commandline.split(" ")[0],commandline.split(" ")[-1]
            clientsocket.send(bytes(cmd+"\r\n"+fileName,encoding="utf-8"))
            with open(fileName,"w") as f: 
                firstPacket=clientsocket.recv(65535)
                items=str(firstPacket,encoding="utf-8").split("\r\n",1)
                fileSize,fileData=int(items[0]) , items[-1]
                while(len(fileData) < fileSize):
                    fileData+=str(clientsocket.recv(65535),encoding="utf-8")
                f.write(fileData)
        else:
            clientsocket.send(bytes(commandline,encoding="utf-8"))
        
        
        
        packet=clientsocket.recv(65535)
        print(str(packet,encoding="utf-8"))

